
import 'package:flutter_elf/config/component_index.dart';
import 'package:flutter_elf/widgets/loadmore_widget.dart';

typedef Widget GetItem(m);
typedef Future<T> FutureData<T>(int page);
class CommonListPage<W extends Widget,T,M> extends StatefulWidget{
  final Widget top;
  final String title;
  final int limit;
  final GetItem getItem;
  final FutureData<T> futureData;


  CommonListPage({this.top, this.title, this.limit,this.getItem, this.futureData});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return CommonListPageState<T,M,W>();
  }
}

class CommonListPageState<T,M,W extends Widget> extends State<CommonListPage>{
  GlobalKey<RefreshIndicatorState> key = GlobalKey();

  int page ;
  List<M> data = [];
  bool isFinish = false;
  Future<void> refresh()async{
    page = 0;
    data.clear();
    dynamic response = await widget.futureData(page);
    if (response?.data?.isNotEmpty ?? false) {
      page++;
      data.addAll(response?.data);
      setState(() {
        if (response?.data?.length == 0) {
          isFinish = true;
        }
      });
    }
  }


  @override
  void initState() {
    super.initState();
    // TODO: implement onCreate
    WidgetsBinding.instance.addPostFrameCallback((_){
//      key.currentState.show();
      refresh();
    });
  }

  Future<bool> loadMore()async{
    dynamic response = await widget.futureData(page);
    if (response?.data?.isNotEmpty ?? false) {
      page++;
      data.addAll(response?.data);
      setState(() {
        globalPrint('一共多少条数据=== 》 ' + data.length.toString());
        if (response?.data?.length == 0) {
          isFinish = true;
        }
      });
      return true;
    }
    return false;
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Column(
      children: <Widget>[
        widget.top == null ? Container() : widget.top,
        Expanded(
          child: RefreshIndicator(
            key: key,
            onRefresh:refresh,
            child: data?.length == 0
                ? Center(
              child: Text('没有数据'),
            )
                : LoadMore(
              whenEmptyLoad: true,
              delegate: DefaultLoadMoreDelegate(),
              textBuilder: DefaultLoadMoreTextBuilder.chinese,
              onLoadMore: loadMore,
              isFinish: data.length % widget.limit != 0 || isFinish,
              child: ListView.builder(
                itemBuilder: (context, i){
                  return widget.getItem(data[i]);
                },
                itemCount: data.length,
              ),
            ),
          ),
        )
      ],
    );
  }
}
